<template>
  <div class="custom-wrap">
    <ButtonArea :style="{ paddingLeft: '0px' }">
      <el-button type="primary" icon="el-icon-plus" :disabled="addBtnState" @click="addOrderHandler">新建</el-button>
      <el-button type="primary" icon="el-icon-edit" :disabled="editBtnState">编辑</el-button>
      <el-button type="primary" icon="el-icon-printer" :disabled="printgdBtnState">打印工单</el-button>
      <el-button type="primary" icon="el-icon-folder" :disabled="saveBtnState" @click="saveBtn">保存</el-button>
      <el-button type="primary" icon="el-icon-refresh-left" @click="goBackHandler">退出</el-button>
      <el-button type="primary" icon="el-icon-delete" :disabled="cancelBtnState">作废</el-button>
    </ButtonArea>
    <div class="left">
      <FormPanel ref="orderPanel" :list="orderList" :cols="1" :labelWidth="90" :isSubmitBtn="false" @formChange="orderChangeHandle" />
      <div :style="{ paddingLeft: '10px', minHeight: '200px' }">
        <LazyLoadTab v-model="assessActiveName" :tabMenus="assessMenus"></LazyLoadTab>
      </div>
    </div>
    <div class="right">
      <FormPanel ref="vownerPanel" :list="vownerList" :cols="3" :labelWidth="110" :isSubmitBtn="false" @formChange="vownerChangeHandle" />
      <ButtonArea :style="{ paddingLeft: '110px' }">
        <el-button type="primary" :disabled="serviceActivity" @click="activityFun()">服务活动</el-button>
        <el-button type="primary" :disabled="serviceActivity" @click="repcombinationFun()">维修组合</el-button>
        <el-button type="primary" @click="historyFun()">维修历史</el-button>
        <el-button type="primary">打印捡料单</el-button>
        <el-button type="primary" @click="importFun()">导入</el-button>
        <el-button type="primary" @click="monitoringFun()">监控</el-button>
        <el-button type="primary" @click="complaintFun()">投诉</el-button>
      </ButtonArea>
      <div :style="{ minHeight: '200px' }">
        <LazyLoadTab v-model="repairActiveName" :tabMenus="repairMenus" @tab-click="tabClickHandle"></LazyLoadTab>
      </div>
    </div>
    <BaseDialog title="选择工单" :visible.sync="workSearchDialog" destroyOnClose>
      <WorkSearch :workNo="WorkSearch_rono" @saveDialog="getSelectWork" @closeDialog="workSearchDialog = false"></WorkSearch>
    </BaseDialog>
    <BaseDialog title="VIN选择" :visible.sync="lincenseSearchDialog" destroyOnClose>
      <LicenseSearch :licenseNo="linSearch_lincense" @saveDialog="getSelectLicense" @closeDialog="lincenseSearchDialog = false"></LicenseSearch>
    </BaseDialog>
    <Drawer :visible.sync="ishistorypop" title="维修历史" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <historypop :getdata="historypopData" @close="closeHistory" />
    </Drawer>
    <Drawer :visible.sync="openVehicleDetailsVisiable" title="车辆明细" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <VehicleDetails :vehicleDetailsVin="vownerList[1].initialValue" @close="closeVehicleDetails" />
    </Drawer>
    <Drawer :visible.sync="isActivity" title="服务活动" destroyOnClose :containerStyle="{ height: '100%', overflow: 'auto' }">
      <Activity :actData="activityData" :repirlist="repirlist" @close1="closeActivity" @ReceiveData="ReceiveData" />
    </Drawer>
    <Drawer :visible.sync="isRepcombination" title="维修组合" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <Repcombination :repirlist="repirlist" @close="closeRepcombination" @WxxmList="WxxmList" />
    </Drawer>
    <!-- 导入按钮 -->
    <BaseDialog :visible.sync="isimportpop" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <ImoprtModal vin="12345678901234533" />
    </BaseDialog>
    <!-- 监控 -->
    <Drawer :visible.sync="ismonitoring" title="监控车辆提醒" width="950" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <MonitoringModal />
    </Drawer>
    <Drawer :visible.sync="visible_ownerInfo" title="车主明细" width="950" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <OwnerInfo :VIN="vownerList[23].initialValue" @close="closeOwnerInfo" />
    </Drawer>
    <Drawer :visible.sync="isComplaint" title="投诉历史" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <Complaint @close="closeComplaint" />
    </Drawer>
  </div>
</template>

<script>
import moment from 'moment';
import { dictionary } from '@/utils/dictMixin';
import { phone } from '@/utils/validate';
import { isEmpty } from '@/utils/index';
import {
  getGdmx,
  queryROByLicense,
  getBxksTime,
  getWxlxSelect,
  getGsdjSelect,
  getBxgsSelect,
  getZdjsSelect,
  getFwgcsSelect,
  getPinpSelect,
  getChexSelect,
  getCheModelSelect,
  postSavelist,
  getFJXM,
  getXSCL,
  getWXCL,
  getWXXM
} from '@/api/repair/business/customer';
import WorkSearch from './searchHelp/WorkSearchHelp';
import LicenseSearch from './searchHelp/LicenseSearchHelp';
import VehicleDetails from './vehicleDetails';
import historypop from '@/pages/repair/business/customer/Repairhistory/historypop.vue';
import Activity from '@/pages/repair/business/customer/combination/activity';
import Repcombination from '@/pages/repair/business/customer/combination/Repcombination';
import Complaint from '@/pages/repair/business/customer/combination/complaint';
import ImoprtModal from '@/pages/repair/business/customer/repairImport/Modal.vue';
import MonitoringModal from '@/pages/repair/business/customer/monitoring/Modal.vue';
import OwnerInfo from '@/pages/repair/business/customer/ownerInfo/ownerInfo';
export default {
  name: 'Customer',
  components: {
    historypop,
    VehicleDetails,
    WorkSearch,
    LicenseSearch,
    Activity,
    Repcombination,
    ImoprtModal,
    MonitoringModal,
    OwnerInfo,
    Complaint
  },
  mixins: [dictionary],
  data() {
    this.config = {
      defaultType: 'default',
      addType: 'add',
      editTyle: 'edit',
      printType: 'print',
      saveTyle: 'save',
      cancelTyle: 'cancel'
    };
    this.saveData = {};
    return {
      pageType: 'default', // 默认类型
      orderList: this.createOrderList(),
      vownerList: this.createVownerList(),
      repairActiveName: '维修项目',
      repairMenus: this.createRepairMenus(),
      assessActiveName: '估价信息',
      assessMenus: this.createAssessMenus(),
      workSearchDialog: false, // 工单搜索弹窗
      WorkSearch_rono: '', // 工单搜索参数
      lincenseSearchDialog: false, // 车辆搜索弹窗
      linSearch_lincense: '', // 车辆搜索参数
      openVehicleDetailsVisiable: false, // 车辆明细弹窗
      ishistorypop: false, // 维修历史弹窗
      isimportpop: false, // 导入按钮弹窗
      ismonitoring: false, // 监控按钮弹窗
      isActivity: false, // 服务活动弹窗
      isRepcombination: false, // 维修组合弹窗
      visible_ownerInfo: false, // 车主弹框
      isComplaint: false, // 投诉按钮弹框

      maintainProList: [], // 维修项目所有数据
      maintainMatList: [], // 维修材料所有数据
      additionalItem: [], // 附加项目所有数据
      repirlist: [], // 维修组合需要数据
      roStatus: null, // 工单状态
      historypopData: {
        vin: 123465
      },
      activityData: {
        LICENSE: '',
        vin: '',
        engineNo: '',
        ownerNo: '',
        MODEL: '',
        BRAND: '',
        SERIES: '',
        CONFIG_CODE: '',
        MILEAGE: '',
        RONO: '',
        SALES_DATE: '',
        createDate: ''
      },
      assessData: {
        maintainPro: [], // 维修项目
        labourAmount: 0, // 工时费
        maintainMat: [], // 维修材料
        repairPartAmount: 0, // 维修材料费
        salePartAmount: 0, // 销售材料费
        additional: [], // 附加项目
        addItemAmount: 0, // 附加项目费
        totalAmount: 0, // 维修金额
        estimateAmount: 0 // 预估金额
      },
      claimData: {}
    };
  },
  computed: {
    addBtnState() {
      const res = this.pageType === this.config.defaultType;
      return !res;
    },
    editBtnState() {
      const res = this.pageType === this.config.editTyle;
      return !res;
    },
    printgdBtnState() {
      const res = this.pageType === this.config.printType;
      return !res;
    },
    saveBtnState() {
      const res = this.pageType === this.config.saveTyle;
      return !res;
    },
    cancelBtnState() {
      const res = this.pageType === this.config.cancelTyle;
      return !res;
    },
    getClaim() {
      let obj = {
        dms_table: [],
        dms_part: [],
        dms_subjoinItem: []
      };
      obj.dms_table = this.assessData.maintainPro.length > 0 ? this.assessData.maintainPro : this.maintainProList[0] ? this.maintainProList[0] : []; // 维修项目
      obj.dms_part = this.assessData.maintainMat.length > 0 ? this.assessData.maintainMat : this.maintainMatList[0] ? this.maintainMatList[0] : []; // 维修材料
      obj.dms_subjoinItem = this.assessData.additional.length > 0 ? this.assessData.additional : this.additionalItem[0] ? this.additionalItem[0] : []; // 附加项目
      return obj;
    },
    // 维修组合 服务活动disabled
    serviceActivity() {
      return this.computedServiceActivity();
    }
  },
  watch: {
    pageType() {
      this.resetFormEditable();
    },
    getClaim: {
      handler(val) {
        console.log('claim', val);
        var claimData = {
          labourAmountS: 0, // 工时费(索赔)
          repairPartAmountS: 0, // 维修材料费(索赔)
          salePartAmountS: 0, // 销售材料(索赔)
          addItemAmountS: 0, // 附加项目(索赔)
          totalAmountS: 0, // 维修金额(索赔)
          estimateAmountS: 0 // 预估金额(索赔)
        };
        for (const item of val.dms_table) {
          if (item.CHARGE_PARTITION_CODE == 'S' && item.LABOUR_AMOUNT) {
            claimData.labourAmountS += parseFloat(item.LABOUR_AMOUNT);
          }
        }
        for (const item of val.dms_part) {
          if (item.CHARGE_PARTITION_CODE == 'S' && item.RECEIVE_AMOUNT) {
            claimData.repairPartAmountS += parseFloat(item.RECEIVE_AMOUNT);
          }
        }
        for (const item of val.dms_subjoinItem) {
          console.log('附加项目');
          if (item.CHARGE_PARTITION_CODE == 'S' && item.ADD_ITEM_PRICE) {
            claimData.addItemAmountS += parseFloat(item.ADD_ITEM_PRICE);
          }
        }
        claimData.estimateAmountS = claimData.labourAmountS + claimData.repairPartAmountS + claimData.salePartAmountS + claimData.addItemAmountS;
        this.claimData = claimData;
        this.assessMenus[1].params.fromData = claimData;

        console.log('claimData', this.claimData);
      },
      deep: true
    }
  },
  mounted() {
    this.getWxlxSelect();
    this.getGsdjSelect();
    this.getBxgsSelect();
    this.getZdjsSelect();
    this.getFwgcsSelect();
    this.getPinpSelect();
    this.resetFormEditable();
  },
  methods: {
    computedServiceActivity(){
      if (this.vownerList[0].initialValue || this.orderList[0].initialValue) {
        this.repairMenus[0].params.lab = false;
        this.repairMenus[1].params.lab = false;
        this.repairMenus[3].params.lab = false;
      } else {
        this.repairMenus[0].params.lab = true;
        this.repairMenus[1].params.lab = true;
        this.repairMenus[3].params.lab = true;
      }
      return this.repairMenus[0].params.lab;
    },
    createRepairMenus() {
      let that = this;
      return [
        {
          title: '维修项目',
          path: 'repair/business/customer/repairTabs/repairPro',
          disabled: true,
          params: {
            dataList: [],
            empty: false,
            lab: false
          },
          on: {
            changeList: function(val) {
              for (const item of val) {
                if (!item.LABOUR_INDEX) item.LABOUR_INDEX = item.LABOUR_CODE + '~' + item.index;
                if (!item.rowKey || item.rowKey == 'S') item.rowKey = 'A';
              }
              that.repairMenus[1].params.dataList = val;
              console.log(val, 'LABOUR_INDEX');
            },
            syncTablelist(val) {
              console.log(val, '维修项目带给主页面');
              for (const item of val) {
                if (!item.LABOUR_INDEX) item.LABOUR_INDEX = item.LABOUR_CODE + '~' + item.index;
                if (!item.rowKey || item.rowKey == 'S') item.rowKey = 'A';
              }
              that.repairMenus[1].params.wxlist = val;
              that.repirlist = val;
              that.assessData.maintainPro = val;
              that.savelabourAmount();
              console.log(val, '维修项目带给主页面-LABOUR_INDEX');
            },
            changeEmpty(val) {
              that.repairMenus[0].params.empty = false;
            }
          }
        },
        {
          title: '维修材料',
          path: 'repair/business/customer/repairTabs/repairStuff',
          disabled: true,
          params: {
            dataList: [],
            // 维修组合 服务活动回显
            list: [],
            // 维修组合 服务活动回显后维修材料选项卡 维修项目名称下拉框内容增加
            wxlist: [],
            empty: false,
            lab: false
          },
          on: {
            syncTablelist(val) {
              for (const item of val) {
                if (!item.rowKey) {
                  item.rowKey = 'A';
                }
              }
              that.assessData.maintainMat = val;
              that.saveRepairPartAmount();
              console.log(val, '维修材料列表');
            },
            changeEmpty(val) {
              that.repairMenus[1].params.empty = false;
            }
          }
        },
        {
          title: '销售材料',
          path: 'repair/business/customer/repairTabs/saleStuff',
          disabled: true,
          params: {
            roNo: '1234',
            empty: false
          },
          on: {
            changeEmpty(val) {
              that.repairMenus[2].params.empty = false;
            }
          }
        },
        {
          title: '附加项目',
          path: 'repair/business/customer/repairTabs/additionalPro',
          disabled: true,
          params: {
            dataList: [],
            empty: false,
            lab: false
          },
          on: {
            syncTablelist(val) {
              console.log(val, '附加项目列表');
              that.assessData.additional = val;
              that.saveAddItemAmount();
            },
            changeEmpty(val) {
              that.repairMenus[3].params.empty = false;
            }
          }
        }
      ];
    },
    tabClickHandle(tab) {
      const { dataList } = this.repairMenus[tab.index].params;
      if (!tab.isLoaded) {
        this.repairMenus[tab.index].params.dataList = [...dataList];
      }
    },
    createAssessMenus() {
      return [
        {
          title: '估价信息',
          path: 'repair/business/customer/assessTabs/priceInfo',
          params: {
            fromData: {}
          }
        },
        {
          title: '索赔估价信息',
          path: 'repair/business/customer/searchHelp/ClaimValuation',
          params: {
            fromData: {}
          }
        }
      ];
    },
    createVownerList() {
      return [
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license',
          unitRender: () => {
            return <el-button icon="el-icon-search" onClick={this.addLicenseHandle}></el-button>;
          },
          onEnter: val => {
            this.linSearch_lincense = val;
            this.addLicenseHandle();
          },
          placeholder: '请输入...',
          rules: [{ required: true, message: '请输入车牌号', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          readonly: true,
          unitRender: () => {
            return <el-button icon="el-icon-search" onClick={this.openVehicleDetails}></el-button>;
          },
          placeholder: '请输入...',
          rules: [{ required: true, message: '请输入VIN号', trigger: 'blur' }]
        },
        {
          type: 'INPUT_NUMBER',
          label: '进厂行驶里程',
          fieldName: 'inMileage',
          placeholder: '请输入...',
          change: val => {
            this.vownerList[5].initialValue = val;
          },
          rules: [{ required: true, message: '请输入进厂行驶里程', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '车主',
          fieldName: 'ownerName',
          unitRender: () => {
            return <el-button icon="el-icon-search" onClick={this.openOwnerInfo}></el-button>;
          },
          placeholder: '请输入...',
          rules: [{ required: true, message: '请输入车主', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '发动机号',
          fieldName: 'engineNo',
          placeholder: '请输入...'
        },
        {
          type: 'INPUT_NUMBER',
          label: '出厂行驶里程',
          fieldName: 'outMileage',
          placeholder: '请输入...'
        },
        {
          type: 'SELECT',
          label: '品牌',
          fieldName: 'brand',
          placeholder: '请选择...',
          itemList: [],
          change: val => {
            this.changePinpSelect(val);
          },
          rules: [{ required: true, message: '请选择品牌', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '车系',
          fieldName: 'series',
          placeholder: '请选择...',
          itemList: [],
          change: val => {
            this.changeChexSelect(val);
          },
          rules: [{ required: true, message: '请选择车系', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '车型',
          fieldName: 'model',
          placeholder: '请选择...',
          itemList: [],
          rules: [{ required: true, message: '请选择车型', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '排量',
          fieldName: 'engineDesc',
          placeholder: '请输入...'
        },
        {
          type: 'SELECT',
          label: '车辆用途',
          fieldName: 'vehiclePurpose',
          placeholder: '请选择...',
          itemList: this.createDictList('1193')
        },
        {
          type: 'INPUT',
          label: '送修人姓名',
          fieldName: 'deliverer',
          placeholder: '请输入...',
          rules: [{ required: true, trigger: 'blur', message: '请输入送修人姓名' }]
        },
        {
          type: 'SELECT',
          label: '送修人性别',
          fieldName: 'delivererGender',
          placeholder: '请选择...',
          itemList: this.createDictList('1006'),
          rules: [{ required: true, message: '请选择送修人性别', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '送修人手机',
          fieldName: 'delivererMobile',
          placeholder: '请输入...',
          rules: [{ required: true, validator: phone, trigger: 'blur', message: '请输入送修人手机' }]
        },
        {
          type: 'INPUT',
          label: '送修人邮箱',
          fieldName: 'delivererEmail',
          placeholder: '请输入...'
        },
        {
          type: 'DATE',
          label: '开票日期',
          fieldName: 'salesDate',
          placeholder: '请输入...'
        },
        {
          type: 'SELECT',
          label: '进厂油料',
          fieldName: 'oilRemain',
          placeholder: '请选择...',
          itemList: this.createDictList('1250')
        },

        {
          type: 'DATE',
          label: '保修开始日期',
          fieldName: 'WRT_BEGIN_DATE_NEW',
          placeholder: '请输入...'
        },
        {
          type: 'INPUT',
          label: '行驶证号',
          fieldName: 'drivingLicense',
          placeholder: '请输入...'
        },
        {
          type: 'DATE',
          label: '上牌日期',
          fieldName: 'licenseDate',
          placeholder: '请输入...'
        },
        {
          type: 'MULTIPLE_CHECKBOX',
          label: '',
          fieldName: 'status',
          itemList: [
            { text: '客户在场', value: '1001' },
            { text: '质检', value: '1002' },
            { text: '带走旧件', value: '1003' },
            { text: '放弃活动', value: '1004' },
            { text: '洗车', value: '1005' },
            { text: '路试', value: '1006' }
          ]
        },
        {
          type: 'TEXT_AREA',
          label: '送修问题',
          fieldName: 'memCustomerDesc',
          placeholder: '请输入...',
          rules: [{ required: true, message: '请填写送修问题', trigger: 'blur' }]
        },
        {
          type: 'TEXT_AREA',
          label: '检查结果',
          fieldName: 'troubleDesc',
          placeholder: '请输入...',
          rules: [{ required: true, message: '请填写检查结果', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '车主编号',
          fieldName: 'ownerNo',
          readonly: true,
          unitRender: () => {
            return <el-button icon="el-icon-search" onClick={this.openOwnerInfo}></el-button>;
          },
          placeholder: '请输入...',
          rules: [{ required: true, message: '请输入车主编号', trigger: 'blur' }]
        },
        {
          type: 'INPUT_NUMBER',
          label: '下次保养里程',
          fieldName: 'nextMaintainMileage',
          placeholder: '请输入...'
        },
        {
          type: 'DATE',
          label: '预计下次保养日期',
          fieldName: 'nextMaintainDate',
          placeholder: '请输入...'
        },
        {
          type: 'SELECT',
          label: '三日电访时间',
          fieldName: 'traceTime',
          placeholder: '请选择...',
          itemList: this.createDictList('1125')
        },
        {
          type: 'INPUT',
          label: '不回访原因',
          fieldName: 'noTraceReason',
          placeholder: '请输入...'
        },
        {
          type: 'DATE',
          label: '上次维修日期',
          fieldName: 'lastMaintainDate',
          placeholder: '请输入...'
        },
        {
          type: 'INPUT',
          label: '送修人电话',
          fieldName: 'delivererPhone',
          placeholder: '请输入...',
          rules: [{ required: true, validator: phone, trigger: 'blur', message: '请输入送修人电话' }]
        },
        {
          type: 'DATE',
          label: '会员卡到期日',
          fieldName: 'memOfMaturity',
          placeholder: '请输入...'
        },
        {
          type: 'DATE',
          label: '故障发生日',
          fieldName: 'troubleOccurDate',
          placeholder: '请输入...'
        },
        {
          type: 'TEXT_AREA',
          label: '备注',
          fieldName: 'remark',
          placeholder: '请输入...'
        },
        {
          type: 'TEXT_AREA',
          label: '备注1',
          fieldName: 'remark1',
          placeholder: '请输入...'
        }
      ];
    },
    createOrderList() {
      return [
        {
          type: 'INPUT',
          label: '工单号',
          fieldName: 'roNo',
          unitRender: () => {
            return <el-button icon="el-icon-search" onClick={this.gdClickHandle}></el-button>;
          },
          onEnter: val => {
            this.WorkSearch_rono = val;
            this.gdClickHandle();
          },
          placeholder: '请输入...'
        },
        {
          type: 'SELECT',
          label: '维修类型',
          fieldName: 'repairType',
          placeholder: '请选择...',
          itemList: [],
          rules: [{ required: true, message: '请选择维修类型', trigger: 'change' }]
        },
        {
          type: 'DATE_TIME',
          label: '开单时间',
          fieldName: 'createDate',
          placeholder: '请输入...'
        },
        {
          type: 'DATE_TIME',
          label: '预开工时间',
          fieldName: 'estimateBeginTime',
          placeholder: '请输入...'
        },
        {
          type: 'DATE_TIME',
          label: '预交车时间',
          fieldName: 'endTimeSupposed',
          placeholder: '请输入...'
        },
        {
          type: 'CHECKBOX',
          label: '自动计算预交车时间',
          fieldName: 'checkIsAutoCalc'
        },
        {
          type: 'SELECT',
          label: '工时单价',
          fieldName: 'labourPrice',
          placeholder: '请选择...',
          itemList: [],
          rules: [{ required: true, message: '请选择工时单价', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '保险公司',
          fieldName: 'insure',
          placeholder: '请选择...',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '车顶号',
          fieldName: 'vehicleTopDesc',
          placeholder: '请选择...',
          itemList: this.createDictList('1284')
        },
        {
          type: 'SELECT',
          label: '安全故障',
          fieldName: 'seriousSafetyStatus',
          placeholder: '请选择...',
          itemList: this.createDictList('1817')
        },
        {
          type: 'SELECT',
          label: '指定技师',
          fieldName: 'technician',
          placeholder: '请选择...',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '进厂原因',
          fieldName: 'inReason',
          placeholder: '请选择...',
          itemList: this.createDictList('1817')
        },
        {
          type: 'INPUT',
          label: '预约单号',
          fieldName: 'bookingOrderNo',
          placeholder: '请输入...'
        },
        {
          type: 'SELECT',
          label: '服务工程师',
          fieldName: 'serviceAdvisor',
          placeholder: '请选择...',
          itemList: [],
          rules: [{ required: true, message: '请选择服务工程师', trigger: 'change' }]
        }
      ];
    },
    addLicenseHandle() {
      if (!this.vownerList[2].initialValue) {
        return this.$notify({
          title: '警告',
          message: '请输入进厂行驶里程',
          type: 'warning'
        });
      }

      for (let i = 0; i < this.vownerList.length; i++) {
        let item = this.vownerList[i];
        if (item.fieldName == 'license') {
          this.linSearch_lincense = item.initialValue;
          break;
        }
      }
      this.lincenseSearchDialog = true;
    },
    // 初始化时间
    setInitDateTime() {
      const nowTime = moment().format('YYYY-MM-DD HH:mm:ss');
      const delayTime = moment()
        .add('hours', 2)
        .format('YYYY-MM-DD HH:mm:ss');
      this.orderList[2].initialValue = nowTime;
      this.orderList[3].initialValue = nowTime;
      this.orderList[4].initialValue = delayTime;
    },
    // 退出按钮
    goBackHandler() {
      this.pageType = 'default';
      this.repairMenus.forEach(x => {
        x.params.empty = true;
      });
      // this.repairMenus = [...this.repairMenus];
    },
    resetFormEditable() {
      if (this.pageType === 'default') {
        // 除了工单号，都不能点
        this.orderList.forEach(x => {
          if (x.fieldName === 'roNo') {
            x.disabled = false;
          } else {
            x.disabled = true;
          }
        });
        this.vownerList.forEach(x => {
          x.disabled = true;
        });
        this.$refs.orderPanel.RESET_FORM();
        this.$refs.vownerPanel.RESET_FORM();
      }
      if (this.pageType === 'add') {
        // 除了车牌号/进厂行驶里程，都不能点
        this.orderList.forEach(x => {
          if (x.fieldName === 'serviceAdvisor') {
            x.disabled = false;
          } else {
            x.disabled = true;
          }
        });
        this.vownerList.forEach(x => {
          if (
            x.fieldName === 'license' ||
            x.fieldName === 'inMileage' ||
            x.fieldName === 'brand' ||
            x.fieldName === 'series' ||
            x.fieldName === 'model' ||
            x.fieldName === 'engineDesc' ||
            x.fieldName === 'vehiclePurpose' ||
            x.fieldName === 'drivingLicense' ||
            x.fieldName === 'licenseDate'
          ) {
            x.disabled = false;
          } else {
            x.disabled = true;
          }
          if (x.fieldName === 'status') {
            x.initialValue = ['1001', '1002', '1005'];
          }
        });
      }
      if (this.pageType === 'edit') {
        this.vownerList.forEach(x => {
          x.disabled = true;
        });
        this.orderList.forEach(x => {
          x.disabled = true;
        });
      }
      this.orderList = [...this.orderList];
      this.vownerList = [...this.vownerList];
    },
    // 新建按钮
    addOrderHandler() {
      this.pageType = 'add';
      this.setInitDateTime();
    },
    async getWxlxSelect() {
      const res = await getWxlxSelect();
      this.orderList[1].itemList = res.data.map(x => ({ value: x.REPAIR_TYPE_CODE, text: x.REPAIR_TYPE_NAME }));
    },
    async getGsdjSelect() {
      const res = await getGsdjSelect();
      this.orderList[6].itemList = res.data.map(x => ({ value: x.LABOUR_PRICE, text: `${x.LABOUR_PRICE}元` }));
    },
    async getBxgsSelect() {
      const res = await getBxgsSelect();
      this.orderList[7].itemList = res.data.map(x => ({ value: x.INSURATION_CODE, text: x.INSURATION_NAME }));
    },
    async getZdjsSelect() {
      const res = await getZdjsSelect();
      this.orderList[9].itemList = res.data.map(x => ({ value: x.EMPLOYEE_NO, text: x.EMPLOYEE_NAME }));
    },
    async getFwgcsSelect() {
      const res = await getFwgcsSelect();
      this.orderList[13].itemList = res.data.map(x => ({ value: x.EMPLOYEE_NO, text: x.EMPLOYEE_NAME }));
    },
    async getPinpSelect() {
      const res = await getPinpSelect();
      this.vownerList[6].itemList = res.map(x => ({ value: x.BRAND_CODE, text: x.BRAND_NAME }));
    },
    async getChexSelect(id) {
      const res = await getChexSelect(id);
      this.vownerList[7].itemList = res.map(x => ({ value: x.SERIES_CODE, text: x.SERIES_NAME }));
    },
    async getCheModelSelect(id) {
      const res = await getCheModelSelect(id);
      this.vownerList[8].itemList = res.map(x => ({ value: x.MODEL_CODE, text: x.MODEL_NAME }));
    },
    // 查询维修项目选项卡
    async getWXXM(id) {
      const res = await getWXXM(id, {});
      for (const item of res) {
        if (item.rowKey) item.rowKey = 'U';
      }
      console.log('维修项目选项卡', res);
      this.repairMenus[0].params.dataList = res;
    },
    // 查询维修材料选项卡
    async getWXCL(id) {
      const res = await getWXCL(id, {});
      for (const item of res) {
        if (item.rowKey) item.rowKey = 'U';
      }
      console.log('维修材料选项卡', res);
      this.repairMenus[1].params.list = res;
    },
    // 查询附加项目选项卡
    async getFJXM(id) {
      const res = await getFJXM(id, {});
      console.log('附加项目选项卡', res);
      this.repairMenus[3].params.dataList = res;
    },
    // 查询销售材料选项卡
    async getXSCL(id) {
      const res = await getXSCL(id, {});
      console.log('销售材料选项卡', res);
    },
    // 品牌下拉框改变时
    changePinpSelect(id) {
      this.clearFormItem(this.vownerList[7]);
      this.clearFormItem(this.vownerList[8]);
      if (!id) return;
      this.getChexSelect(id);
    },
    // 车系下拉框改变时
    changeChexSelect(id) {
      this.clearFormItem(this.vownerList[8]);
      if (!id) return;
      this.getCheModelSelect(id);
    },
    // 清空下拉框表当控件的值和下拉列表
    clearFormItem(item) {
      item.initialValue = undefined;
      item.itemList = [];
    },
    // 把相关组件回带的数据，赋值给表单元素
    syncFormListData(dataList) {
      // dataList 格式 -> [{ fieldName: 'xxx', value: 'xxx' }, ...]
      const formList = [...this.orderList, ...this.vownerList];
      const formFieldNames = formList.map(x => x.fieldName);
      dataList.forEach(x => {
        if (formFieldNames.includes(x.fieldName)) {
          let target = formList.find(k => k.fieldName === x.fieldName);
          if (!target) return;
          target.initialValue = x.value;
          if (target.fieldName === 'license' || target.fieldName === 'ownerName' || target.fieldName === 'salesDate') {
            target.disabled = true;
          } else {
            target.disabled = false;
          }
        }
      });

      console.log(dataList);
    },
    // 工单号搜索帮助按钮
    gdClickHandle() {
      for (let i = 0; i < this.orderList.length; i++) {
        let item = this.orderList[i];
        if (item.fieldName == 'roNo') {
          this.WorkSearch_rono = item.initialValue;
          break;
        }
      }

      this.workSearchDialog = true;
    },
    orderChangeHandle(val) {
      this.saveData = Object.assign(this.saveData, val);
      console.log('工单信息：', val);
    },
    vownerChangeHandle(val) {
      this.saveData = Object.assign(this.saveData, val);
      console.log('车主信息：', val);
    },
    // 工单查询按钮
    async getSelectWork(arr) {
      this.historypopData = arr[0];
      this.workSearchDialog = false;

      if (!arr.length) {
        return;
      }
      console.log('工单', arr);
      this.repairMenus.forEach(x => {
        x.disabled = false;
      });
      let obj = arr[0];
      // 工单号选择带出数据传给服务活动
      this.activityData = {
        LICENSE: obj.LICENSE,
        vin: obj.VIN,
        engineNo: obj.ENGINE_NO,
        ownerNo: obj.OWNER_NO,
        MODEL: obj.MODEL,
        BRAND: obj.BRAND,
        SERIES: obj.SERIES,
        CONFIG_CODE: obj.CONFIG_CODE,
        MILEAGE: obj.MILEAGE,
        RONO: obj.RO_NO,
        SALES_DATE: moment(obj.SALES_DATE).format('YYYY-MM-DD'),
        createDate: moment(obj.RO_CREATE_DATE).format('YYYY-MM-DD HH:mm:ss')
      };
      // 根据工单号，调取维修项目..等选项卡内容
      this.getWXXM(obj.RO_NO);
      this.getWXCL(obj.RO_NO);
      this.getFJXM(obj.RO_NO);
      this.getXSCL(obj.RO_NO);
      this.roStatus = obj.RO_STATUS;
      console.log('工单状态', this.roStatus);
      // 选择工单号，更新保修开始日期
      let str = await getBxksTime(obj.VIN);
      let date = str.split('#').shift();
      this.vownerList.some(item => {
        if (item.fieldName === 'WRT_BEGIN_DATE_NEW') {
          item.initialValue = date;
        }
      });

      // 查询工单明细
      let params = {
        roNo: obj.RO_NO
      };
      let objD = await getGdmx(params);

      this.dataProcess(objD);
      this.pageType = 'save';
    },
    async getSelectLicense(arr) {
      this.lincenseSearchDialog = false;

      if (!arr.length) {
        return;
      }
      console.log('aaa', arr);
      let obj = arr[0];
      let flag = true;
      // vin选择带出数据传给服务活动
      this.activityData = {
        LICENSE: obj.LICENSE,
        vin: obj.VIN,
        engineNo: obj.ENGINE_NO,
        ownerNo: obj.OWNER_NO,
        MODEL: obj.MODEL,
        BRAND: obj.BRAND,
        SERIES: obj.SERIES,
        CONFIG_CODE: obj.CONFIG_CODE,
        MILEAGE: obj.MILEAGE,
        // RONO:obj.LICENSE,
        SALES_DATE: moment(obj.SALES_DATE).format('YYYY-MM-DD')
        // createDate:
      };

      if (!isEmpty(obj.VIN)) {
        let params = {
          vin: obj.VIN,
          roStatus: '12551001'
        };
        let res = await queryROByLicense(params);

        if (!isEmpty(res.data)) {
          flag = false;

          this.$confirm('此车牌存在在修车辆，是否继续新建工单？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              this.dataProcess(obj);
              this.fun();
            })
            .catch(() => {
              return;
            });
        } else {
          if (flag) {
            this.dataProcess(obj);
          }
          this.fun();
        }
      } else {
        if (flag) {
          this.dataProcess(obj);
        }
        this.fun();
      }
    },
    // 选择车牌号之后，车主和车牌号disabled
    fun() {
      this.vownerList.forEach(x => {
        if (x.fieldName === 'license' || x.fieldName === 'ownerName') {
          x.disabled = true;
        } else if (
          x.fieldName === 'outMileage' ||
          x.fieldName === 'deliverer' ||
          x.fieldName === 'delivererGender' ||
          x.fieldName === 'delivererMobile' ||
          x.fieldName === 'delivererEmail' ||
          x.fieldName === 'oilRemain' ||
          x.fieldName === 'memCustomerDesc' ||
          x.fieldName === 'troubleDesc' ||
          x.fieldName === 'delivererPhone' ||
          x.fieldName === 'remark' ||
          x.fieldName === 'remark1'
        ) {
          x.disabled = false;
        }
      });
      // 选择车牌号之后，维修类型和预开工时间 工时单价 保险公司 取消disabled
      this.orderList.forEach(x => {
        if (
          x.fieldName === 'repairType' ||
          x.fieldName === 'labourPrice' ||
          x.fieldName === 'estimateBeginTime' ||
          x.fieldName === 'insure' ||
          x.fieldName === 'vehicleTopDesc' ||
          x.fieldName === 'seriousSafetyStatus' ||
          x.fieldName === 'technician' ||
          x.fieldName === 'inReason'
        ) {
          x.disabled = false;
        }
      });
      // 选择车牌号后 维修项目维修材料等 选项卡可切换
      this.repairMenus.forEach(x => {
        x.disabled = false;
      });
      this.pageType = 'save';
    },

    // 工单搜索，车辆搜索 字段处理，push到表单中
    dataProcess(obj) {
      const brand = obj.BRAND;
      const series = obj.SERIES;
      this.changePinpSelect(brand);
      this.changeChexSelect(series);

      let arimsArr = [];
      for (let [key, val] of Object.entries(obj)) {
        let param = {
          fieldName: this.camelcase(key),
          value: val
        };

        let arr = ['createdAt', 'roCreateDate', 'estimateBeginTime', 'endTimeSupposed', 'firstInDate', 'nextMaintainDate', 'lastMaintainDate', 'licenseDate', 'salesDate'];

        arr.some(item => {
          if (param.fieldName === item) {
            param.value = moment(param.val).format('YYYY-MM-DD HH:mm:ss');
            return true;
          }
        });

        arimsArr.push(param);
      }

      // const checkArr = [
      //   {
      //     label: 'isCustomerInAsc',
      //     value: 'checkIsFactory'
      //   },
      //   {
      //     label: 'isSeasonCheck',
      //     value: 'checkIsQuality'
      //   },
      //   {
      //     label: 'isTakePartOld',
      //     value: 'checkIsTake'
      //   },
      //   {
      //     label: 'isAbandonActivity',
      //     value: 'checkIsGiveUp'
      //   },
      //   {
      //     label: 'isWash',
      //     value: 'checkIsWash'
      //   },
      //   {
      //     label: 'needRoadTest',
      //     value: 'checkIsRoad'
      //   }
      // ];

      // let checkInitValue = [];
      // for (let i = 0; i < checkArr.length; i++) {
      //   arimsArr.some(item => {
      //     if (item.fieldName === checkArr[i].label && this.CheckBy1278(item.value)) {
      //       checkInitValue.push(checkArr[i].value);
      //     }
      //   });
      // }

      // if (!isEmpty(checkInitValue)) {
      //   let param = {
      //     fieldName: 'status',
      //     value: checkInitValue
      //   };

      //   arimsArr.push(param);
      // }

      const addArr = [
        {
          label: 'repairTypeCode',
          value: 'repairType'
        },
        {
          label: 'customerDesc',
          value: 'troubleDesc'
        },
        {
          label: 'customerDesc',
          value: 'memCustomerDesc'
        },
        {
          label: 'roCreateDate',
          value: 'createDate'
        }
      ];

      for (let i = 0; i < addArr.length; i++) {
        arimsArr.some(item => {
          if (item.fieldName === addArr[i].label) {
            let param = {
              fieldName: addArr[i].value,
              value: item.value
            };

            arimsArr.push(param);
            return true;
          }
        });
      }

      this.syncFormListData(arimsArr);
    },
    openVehicleDetails() {
      this.openVehicleDetailsVisiable = true;
    },
    closeVehicleDetails(val, vehicleDetailsTotal) {
      this.openVehicleDetailsVisiable = val;
      if (vehicleDetailsTotal) {
        let vehicleDetailsArr = [];
        for (let [key, val] of Object.entries(vehicleDetailsTotal)) {
          let param = {
            fieldName: this.camelcase(key),
            value: val
          };
          vehicleDetailsArr.push(param);
        }
        this.syncFormListData(vehicleDetailsArr);
      }
    },
    closeHistory(val) {
      this.ishistorypop = false;
    },
    historyFun() {
      this.ishistorypop = true;
    },

    // 驼峰转换  RO_NO --> roNo
    camelcase(str) {
      let arr = str.split('_');
      let upper = arr.map((val, index) => {
        let lowStr = val.toLowerCase();

        if (index) {
          lowStr = lowStr.charAt(0).toLocaleUpperCase() + lowStr.slice(1);
        }

        return lowStr;
      });

      return upper.join('');
    },
    importFun() {
      this.isimportpop = true;
    },
    monitoringFun() {
      this.ismonitoring = true;
    },
    activityFun() {
      this.isActivity = true;
    },
    closeActivity(val) {
      this.isActivity = val;
    },
    repcombinationFun() {
      this.isRepcombination = true;
    },
    closeRepcombination(val) {
      this.isRepcombination = val;
    },
    complaintFun() {
      this.isComplaint = true;
    },
    closeComplaint(val) {
      this.isComplaint = val;
    },
    // 接收服务活动确定返回
    ReceiveData(val) {
      this.isActivity = false;

      // 维修项目
      this.repairMenus[0].params.dataList = val.res1;
      this.maintainProList.push(val.res1);
      // 维修材料
      this.repairMenus[1].params.list = val.res2;
      this.maintainMatList.push(val.res2);
      // 附加项目
      this.repairMenus[3].params.dataList = val.res3;
      this.additionalItem.push(val.res3);
      console.log('val', this.maintainMatList);
    },
    // 接收维修组合确定返回
    WxxmList(val) {
      // this.isRepcombination = false;
      // 维修项目
      this.repairMenus[0].params.dataList = val.list1;
      this.maintainProList.push(val.res1);
      // 维修材料
      this.repairMenus[1].params.list = val.list2;
      this.maintainMatList.push(val.res2);
      console.log('val.res2', val.list1);
    },
    openOwnerInfo() {
      this.visible_ownerInfo = true;
    },
    closeOwnerInfo() {
      this.visible_ownerInfo = false;
    },
    // 数据从1278状态转化成复选框选择
    CheckBy1278(val) {
      if (!isEmpty(val) && val == '10041001') {
        return true;
      }
      return false;
    },
    // 保存
    async saveBtn() {
      this.$refs.orderPanel.SUBMIT_FORM();
      this.$refs.vownerPanel.SUBMIT_FORM();
      let objs = {
        checkIsFactory: '',
        checkIsQuality: '',
        checkIsTake: '',
        checkIsGiveUp: '',
        checkIsWash: '',
        checkIsRoad: '',
        dms_table: this.assessData.maintainPro.length > 0 ? this.assessData.maintainPro : this.maintainProList[0] ? this.maintainProList[0] : [], // 维修项目
        dms_sales: [], // 销售材料
        dms_part: this.assessData.maintainMat.length > 0 ? this.assessData.maintainMat : this.maintainMatList[0] ? this.maintainMatList[0] : [], // 维修材料
        dms_subjoinItem: this.assessData.additional.length > 0 ? this.assessData.additional : this.additionalItem[0] ? this.additionalItem[0] : [], // 附加项目
        addItemAmount: this.assessData.addItemAmount, // 附加项目费
        estimateAmount: this.assessData.estimateAmount, // 预估金额
        insurationCode: '', // 理赔单号
        roStatus: this.roStatus ? this.roStatus : null, // 理赔单号 工单状态
        labourAmount: this.assessData.labourAmount, // 工时费
        // labourPrice: '0', //工时单价
        repairPartAmount: this.assessData.repairPartAmount, // 维修材料费
        salePartAmount: this.assessData.salePartAmount, // 销售材料费
        totalAmount: this.assessData.totalAmount // 维修金额
      };
      let obj = JSON.parse(JSON.stringify(objs));
      // for (const item of obj.dms_part) {
      //   item.LABOUR_CODE = item.LABOUR_CODE.substr(0, item.LABOUR_CODE.indexOf('~'));
      // }
      for (const item of obj.dms_part) {
        item.LABOUR_CODE = item.LABOUR_CODE + '~' + item.index;
      }
      for (const item of obj.dms_table) {
        item.LABOUR_INDEX = String(item.index);
      }
      console.log('保存', obj.dms_part);
      this.saveData.licenseDate = moment(this.saveData.licenseDate).format('YYYY-MM-DD');
      this.saveData.salesDate = moment(this.saveData.salesDate).format('YYYY-MM-DD');
      //  console.log('保存',this.saveData)
      this.saveData.status.find(item => {
        if (item == 1001) obj.checkIsFactory = '10041001';
        if (item == 1002) obj.checkIsQuality = '10041001';
        if (item == 1003) obj.checkIsTake = '10041001';
        if (item == 1004) obj.checkIsGiveUp = '10041001';
        if (item == 1005) obj.checkIsWash = '10041001';
        if (item == 1006) obj.checkIsRoad = '10041001';
      });
      this.saveData = {
        ...this.saveData,
        ...obj
      };
      for (var i in this.saveData) {
        if (!this.saveData[i] && this.saveData[i] != 0) {
          delete this.saveData[i];
        }
      }
      let res = await postSavelist(this.saveData);
      console.log('保存后', this.saveData);
      // console.log('保存返回',a)
      if (res.RoNo) {
        this.$notify.success({ title: '提示信息', message: '保存成功!' });
        this.orderList[0].initialValue = res.RoNo;
        this.pageType = !this.pageType;
        this.pageType = 'edit';
      } else {
        this.$notify.error({ title: '提示信息', message: res.errMsg || '保存失败!' });
      }
    },
    savelabourAmount() {
      this.assessData.labourAmount = 0;
      for (const item of this.assessData.maintainPro) {
        if (!item.CHARGE_PARTITION_CODE && item.LABOUR_AMOUNT != '') {
          this.assessData.labourAmount += parseFloat(item.LABOUR_AMOUNT);
        }
      }
      // console.log('gsf',this.assessData.labourAmount)
      this.totalCost();
    },
    saveRepairPartAmount() {
      this.assessData.repairPartAmount = 0;
      for (const item of this.assessData.maintainMat) {
        if (!item.CHARGE_PARTITION_CODE && item.RECEIVE_AMOUNT) {
          this.assessData.repairPartAmount += parseFloat(item.RECEIVE_AMOUNT);
        }
      }
      // console.log('clf',this.assessData.repairPartAmount)
      this.totalCost();
    },
    saveAddItemAmount() {
      this.assessData.addItemAmount = 0;
      for (const item of this.assessData.additional) {
        if (!item.CHARGE_PARTITION_CODE && item.ADD_ITEM_PRICE) {
          this.assessData.addItemAmount += parseFloat(item.ADD_ITEM_PRICE);
        }
      }
      // console.log('fjxmf',this.assessData.addItemAmount)
      this.totalCost();
    },
    totalCost() {
      this.assessData.estimateAmount = this.assessData.labourAmount + this.assessData.repairPartAmount + this.assessData.salePartAmount + this.assessData.addItemAmount;
      this.assessMenus[0].params.fromData = this.assessData;
    }
  }
};
</script>

<style lang="less">
.custom-wrap {
  position: relative;
  padding-bottom: @modulePadding;
  .left {
    position: absolute;
    left: 0;
    width: 280px;
    border: 1px solid @borderColor;
    border-radius: @borderRadius;
    box-shadow: @boxShadow;
    padding: @modulePadding;
    padding-left: 0;
  }
  .right {
    margin-left: 300px;
    border: 1px solid @borderColor;
    border-radius: @borderRadius;
    box-shadow: @boxShadow;
    padding: @modulePadding;
  }
}
</style>
